const Router = require("koa-Router");
const router = new Router();
const path = require("path");
const fs = require("fs");
const jwt=require("jsonwebtoken");
let userJSON = path.join(__dirname, "../", "Data", "user.json");
let roleJSON = path.join(__dirname, "../", "Data", "role.json");
let authJSON = path.join(__dirname, "../", "Data", "auth.json");
router.post("/login", (ctx) => {
  let { username, password } = ctx.request.body;
  let userData = JSON.parse(fs.readFileSync(userJSON, "utf8"));
  let flag = userData.some(
    (item) => item.username == username && item.password == password
  );
  let token=jwt.sign(
    {
      data: { username, password },
    },
    "secret",
    { expiresIn: 60 * 60 }
  );
  if (!flag) {
    return ctx.body={
        code: 401,
        message: "用户名或密码错误"
      }
    }
    let user = userData.find((item) => item.username == username);
  const roleData = JSON.parse(fs.readFileSync(roleJSON, "utf-8"));
  const role = roleData.find((item) => item.id === user.roleId);
  let authData = JSON.parse(fs.readFileSync(authJSON));
  //   调试是否获取成功
  //   console.log(user,roleData,role);
  if (role.auths !== "*") {
    authData = authData.filter((item) => role.auths.includes(item.id));
  }
  return (ctx.body = {
    code: 200,
    msg: "登录成功",
    username,
    token,
    userId: user.id,
    auth: authData,
  });
});
      
module.exports = router;
